<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <h1>{{val}}</h1>
        <button @click="handleClick">点击侦听val</button>
    </div>
</body>

</html>
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
<script>

    //api方式侦听:可以通过特定的条件,对数据进行侦听
    //比如:点击按钮对val进行侦听
    let vm = new Vue({
        el: "#app",
        data: {
            val: "李雷"
        },
        watch: {
            //让侦听函数立即调用
            // val(newVal, oldVal) {
            //     console.log('newVal', newVal)
            //     console.log('oldVal', oldVal)
            // }01

            // val: {
            //     handler(newVal, oldVal) {
            //         console.log('newVal', newVal)
            //         console.log('oldVal', oldVal)
            //     },
            //     //立即调用watch函数
            //     immediate: true
            // }
        },
        methods: {
            handleClick() {
                //以api的方式调用watch
                this.$watch('val', function (newVal, oldVal) {
                    console.log('newVal', newVal)
                    console.log('oldVal', oldVal)
                })
            }
        }
    })


</script>